import threading
import time
from queue import Queue

import pyautogui

from client.tdmg import manager


class KeyPressManager:
    def __init__(self):
        self.queue = Queue()
        self.stop_event = threading.Event()
        manager.start_thread(target=self.press_key_thread, args=(manager.get_stop_event(),))
        # self.thread = threading.Thread(target=self.press_key_thread)
        # self.thread.start()

    def press_key_thread(self,stop_event):
        while not stop_event.is_set():
            try:
                key, duration = self.queue.get(timeout=0.1)  # 从队列中获取按键事件
                self.execute_key_press(key, duration)
            except Exception as e:
                pass  # 可以根据需要处理队列异常
            time.sleep(0.1)  # 控制循环频率

    def execute_key_press(self, key, duration):
        pyautogui.keyDown(key)
        time.sleep(duration)
        pyautogui.keyUp(key)

    def set_key(self, key, duration):
        self.queue.put((key, duration))

    def clear_key(self):
        self.queue.queue.clear()

    def stop_key_press(self):
        self.queue.queue.clear()
        self.stop_event.set()
        self.thread.join()


# 示例类
class MyClass:
    def __init__(self):
        self.key_pro = KeyPressManager()
        self.skill_sequence = ["E", "X"]  # 按键序列

    def releaseSkill2(self):
        self.key_pro.set_key("E", 0)  # 每个技能按键持续 0.3 秒
        self.key_pro.set_key("X", 1.5)  # 每个技能按键持续 0.3 秒
        self.key_pro.clear_key()
        # time.sleep(0.1)  # 等待按键持续时间EX


# 使用示例
# my_object = MyClass()
# while True:
#     my_object.releaseSkill2()

    # time.sleep(0.1)  # 等待一小段时间，确保事件有机会被处理

# 示例用法
if __name__ == "__main__":
    # 示例使用
    # manager = KeyPressManager()
    # while True:
    #     manager.press_key_in_background('a', 10)  # 持续按下'a'键10秒
    #     time.sleep(2)  # 等待2秒后取消按键
    #     manager.stop_key()
    #     print("Key press stopped")
    #     time.sleep(5)  # 等待5秒后重新按键aaaa
    #
    #     # print(6666)
    pass
